
var localfilmlist = []; // 保存id
$(function (){
    if('WebSocket' in window){  /*判断浏览器是否支持WebSocket接口*/
        /*创建创建 WebSocket 对象，协议本身使用新的ws://URL格式*/
        // console.log(window.location.host);
        // var str = "ws://10.210.20.141:9000/fiddler/websocket/"+randomString();
        var str = "ws://"+window.location.host+"/websocket?id="+randomString();
        // console.log(str);
        var Socket = new WebSocket(str);
        /*连接建立时触发*/
        Socket.onopen = function () {
            // var received_msg = ev.data;
            // console.log(received_msg);
            // alert("连接已建立，可以进行通信")
        };
        /*客户端接收服务端数据时触发*/
        Socket.onmessage = function (ev) {
            var received_msg = ev.data; /*接受消息*/
            // console.log(received_msg);
            var json_data = eval("(" + received_msg + ")")
            if (json_data.type=='data'){
                new_data = json_data.list;
                // console.log(new_data[0]['name']);
                // console.log(new_data.length);
                updatedata(new_data);
            }else if(json_data.type=='delete'){
                id = json_data.id;
                if(localfilmlist.indexOf(id) !=-1){
                    // console.log(id);
                    localfilmlist.splice(localfilmlist.indexOf(id),1);
                    $('#'+id).remove();
                }else{
                  // console.log('id不存在'+id);
                }
            }
        };
        /*连接关闭时触发*/
        Socket.onclose = function () {
            // mes.innerHTML += "<br>连接已经关闭...";
        };
    }else{
        /*浏览器不支持 WebSocket*/
        alert("您的浏览器不支持 WebSocket!");
    }
    function WebSocketSend() {
        /*form 里的Dom元素(input select checkbox textarea radio)都是value*/
        var send_msg = document.getElementById('text').value;
        //或者JQ中获取
        // var send_msg = $("#text").val();
        /*使用连接发送消息*/
        Socket.send(send_msg);
    }
})
function randomString(){
    var str=Math.random().toString(36).substring(2);
    // console.log(str);
    return str;
}
function updatedata(res){
    for(var i=0;i<res.length;i++){
        if(res[i]["status"]==0 || res[i]["status"]==3 ||res[i]["status"]==5 || res[i]["status"]==14){
            var status = '开始';
        }
        else if (res[i]["status"]==6 || res[i]["status"]==7){
            var status = '暂停';
        }else if(res[i]["status"]==8 || res[i]["status"]==9){
            var status = '开始';
        }else{
            var status = '';
        }
        if(res[i]['status']==10 || res[i]['status']==12){
            var append = '导入';
            var redownload = '重新下载';
        }else{
            var append = '导入';
            var redownload = '重新下载';
        }
        // 计算百分比
        if(res[i]["type"]=='m3u8'){
            if(res[i]["total"]==0){
                var percent = '--';
            }else{
                var percent = (res[i]["done"]/res[i]["total"]*100).toFixed(1)+'%';
            }
        }else if(res[i]["type"]=='mp4'){
            if(res[i]["content_length"]==0){
                var percent = '--';
            }else{
                var percent = (res[i]["done_length"]/res[i]["content_length"]*100).toFixed(1)+'%';
            }
        }
        // 计算速度（不准确）
        if(res[i]['done_length']==0){
            var size = '--';
            var speed = '';
        }else{
            var size = (res[i]['done_length']/1024/1024).toFixed(1)+'m';
            if(res[i]["status"]==7 || res[i]["status"]==8){
                var speed = (res[i]['done_length']-res[i]['pre_done_length'])/1024;
                if(speed>=1024){
                    speed = (speed/1024).toFixed(1)+'Mb/s';
                }else{
                    speed = speed.toFixed(1)+'Kb/s';
                }
            }else{
                var speed = '';
            }
        }
        if(res[i]["msg"]){
            var msg = res[i]["msg"];
        }else{
            var msg = speed;
        }
        // 播放链接
        var play_index = '/customplay?id='+res[i]["id"]+'&name='+res[i]["name"]+'&type='+res[i]["type"];
        if(localfilmlist.indexOf(res[i]['id']) ==-1){
            // 首次进入时，下载记录加载到不同列表中
            var con = '<div id='+res[i]["id"]+' type="'+res[i]["type"]+'" class="form-group col-md-12" style="font-size: 10px;background: none;border-color: #ebccd1;box-shadow: 0px 1px 2px 0px rgba(50, 50, 50, 0.25);margin-bottom: 5px;overflow:hidden;text-overflow:ellipsis;">\
                              <div style="float:left;width: 60%;margin-bottom: 0px;padding-right: 8px;">\
                                <div>\
                                  <label for="input_filename" name="name" ondblclick="copyData(this);" style="width:90%;line-height: 16px;margin-bottom: 0;font-size: inherit;">'+res[i]["name"]+' ('+res[i]["author"]+')</label>\
                                  <a name="msg" style="float: right;color: red;text-decoration: none;font-size: small;font-weight: 400;">'+msg+'</a></div>\
                                <a name="url" ondblclick="copyData(this);" style="text-decoration: none;">'+res[i]["url"]+'</a></div>\
                              <div style="float:left;width: 20%;margin-bottom: 0px;padding-right: 8px;padding-left: 8px;line-height: 28px;color: #050582;">\
                                <label for="input_filename" name="speed" style="width: 33%;font-weight: 400;color: #3a9303;margin:2px 0px;">'+""+'</label>\
                                <label for="input_filename" name="percent" style="width: 33%;padding-left: 15px;font-weight: 500;margin:2px 0px;">'+percent+'</label>\
                                <label for="input_filename" name="size" style="float: right;font-weight: 400;color: #2f2f30;margin:2px 0px;">'+size+'</label></div>\
                              <div style="float: right;padding-left: 8px;width: 200px;text-align: center;padding-right: 8px;line-height: 28px;font-size: 12px;background: #c4c4d9;margin-top: 2px;margin-bottom: 2px;">\
                                <a name="play" href="'+play_index+'" target="_blank"  style="float: left;">播放</a>\
                                <a name="redownload" value="'+res[i]["id"]+'" onclick="redownload(this);" style="">'+redownload+'</a>\
                                <a name="append" onclick="append(this);"  style="margin-left: 10px;">'+append+'</a>\
                                <a name="stop" value="'+res[i]["status"]+'" onclick="stop(this);" style="margin-left: 10px;">'+status+'</a>\
                                <a name="delete" onclick="dele(this);" style="float: right;">删除</a></div>\
                          </div>';
            if(res[i]['status']==10 || res[i]['status']==12){
                $('#downloaded-films').append(con);
            }else{
                $('#download-films').append(con);
            }
            localfilmlist.push(res[i]["id"]);
        }else{
            // 否则只要更新状态
            // console.log();
            var obj = $("#"+res[i]['id']);

            // $('label[name$="name"]',obj).text(res[i]['name']);
            $('a[name$="url"]',obj).text(res[i]['url']);
            $('a[name$="msg"]',obj).text(msg);
            // $('label[name$="speed"]',obj).text(speed);
            $('label[name$="percent"]',obj).text(percent);
            $('label[name$="size"]',obj).text(size);
            $('a[name$="append"]',obj).text(append);
            $('a[name$="stop"]',obj).text(status);
            $('a[name$="stop"]',obj).attr('value',res[i]["status"]);
        }
        // 有新的下载完成、合并完成时
        if(res[i]['status']==10 ||res[i]['status']==12){
            var _id = res[i]["id"];
            if($('#'+_id).parent().attr('id')=='download-films'){
                $('#downloaded-films').append($('#'+_id));
            }
        }
    }
}
